<template>
    <div class="conditional-config">
        <div class="conditional-config-title">
            设置数据查询条件
        </div>
        <div class="conditional-config-content" v-loading="loading">
            <div v-for="(conditionSet, conditionSet_index) in state.currentNodeInfoFront.options.conditionList" class="conditional-config-set" :key="conditionSet_index">
                <div v-if="conditionSet_index != 0" class="conditional-config-title-or">或</div>
                <div class="conditional-config-set-content">
                    <div class="conditional-config-set-content-title">
                        <div>条件组</div>
                        <el-button 
                            type="text" 
                            icon="el-icon-delete"
                            @click="deleteCondition(conditionSet_index)"
                            v-if="state.currentNodeInfoFront.options.conditionList.length > 1"
                        ></el-button>
                    </div>
                    <div class="conditional-config-set-content-content">
                        <div v-for="(condition, index) in conditionSet" class="conditional-config-item" :key="index">
                            <div v-if="index != 0" class="conditional-config-title-and">且</div>
                            <div class="conditional-config-item-content">
                                <div class="conditional-config-item-content-title">
                                    <div>条件</div>
                                    <el-button 
                                        type="text" 
                                        icon="el-icon-delete"
                                        @click="deleteConditionChildren(conditionSet_index, index)"
                                    ></el-button>
                                </div>
                                <div class="conditional-config-item-content-content">
                                    <el-cascader 
                                        class="conditional-config-select-max" 
                                        popper-class="conditional-config_cascader-popover"
                                        v-model="condition.toEnName"
                                        :options="filedList" 
                                        placeholder="请选择触发应用字段" 
                                        filterable
                                        :props="{ checkStrictly: true, label:'cnName', value:'enName', emitPath:false, expandTrigger: 'hover', }"
                                        @change="handleSelectionChange($event, conditionSet_index, index)"
                                        ref="cascaderHandle"
                                    >
                                        <template slot-scope="{ data }">
                                            <div class="item" :class="data.cnName.length > 12 ? 'item-overflow' : ''" :title="data.cnName">{{ data.cnName }}</div>
                                        </template>
                                    </el-cascader>
                                    <el-select class="conditional-config-select-small" v-model="condition.operate"
                                        placeholder="判断符" :disabled="!condition.toEnName" @change="condition.value = []">
                                        <el-option v-for="i in findData(filedList, condition.toEnName).operateList || []" :label="i.cnName" :value="i.enName" :key="i.enName"></el-option>
                                    </el-select>
                                    <el-select class="conditional-config-select-small" v-model="condition.valueType"
                                        v-if="!condition.operate || (condition.operate != 'NOT_EMPTY' && condition.operate != 'EMPTY')"
                                        placeholder="固定值" :disabled="!condition.toEnName" @change="condition.value = []">
                                        <el-option v-for="i in findData(filedList, condition.toEnName).valueTypeList || []" :label="i.cnName" :value="i.enName" :key="i.enName"></el-option>
                                    </el-select>
                                    <fixedInput
                                        class="conditional-config-select-max"
                                        v-if="condition.valueType == '1' && condition.operate != 'NOT_EMPTY' && condition.operate != 'EMPTY' && filedList.length"
                                        v-model="condition.value"
                                        :field="findData(filedList, condition.toEnName)"
                                        :operator="condition.operate"
                                        @input="condition.value = $event"
                                    ></fixedInput>
                                    <ConnectorModuleRuleFormItemApp
                                        class="conditional-config-select-max"
                                        v-else-if="condition.valueType == '3' && condition.operate != 'NOT_EMPTY' && condition.operate != 'EMPTY'"
                                        :currentToField="findData(filedList, condition.toEnName)"
                                        :isDisabledFromFieldSelect="false"
                                        :fromFieldList="filedList"
                                        :fromBizTypeName="findData(filedList, condition.toEnName).cnName"
                                        :value="condition.value[0]"
                                        @change="handleChange($event, conditionSet_index, index)"
                                    />
                                </div>
                            </div>
                            <div v-if="index == conditionSet.length - 1">
                                <el-button type="text" icon="el-icon-plus"
                                    @click="addConditionChildren(conditionSet_index, index)">添加且</el-button>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="conditionSet_index == state.currentNodeInfoFront.options.conditionList.length - 1">
                    <el-button type="text" icon="el-icon-plus"
                        @click="addCondition(conditionSet_index)">添加过滤条件</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { getConditionConfig } from '@src/modules/trigger/api/trigger.js'
import ConnectorModuleRuleFormItemApp from '@src/modules/connector/components/rule-form/item-form-app'
import fixedInput from './fiexdInput.vue'
import state from '@src/modules/trigger/view/setting/util/state.js'
import dayjs from 'dayjs'

export default {
    name: 'ConditionConfig',
    computed: {
        state() {
            return state;
        },
    },
    watch: {
        'state.currentNodeInfoFront.options': {
            handler() {
                if (!state.currentNodeInfoFront.options?.conditionList) {
                    return;
                }
                this.changeContent();
            },
            deep: true
        }
    },
    components: {
        ConnectorModuleRuleFormItemApp,
        fixedInput,
    },
    created() {
        this.loading = true;
        if (!(state.currentNodeInfoFront?.options?.conditionList || []).length) {
            this.$set(state.currentNodeInfoFront, 'options', {
                ...state.currentNodeInfoFront?.options,
                convertType: "mapping",
                conditionList: [
                    [
                        {
                            toEnName: '',
                            operate: '',
                            valueType: '',
                            value: [],
                        }
                    ]
                ]
            });
        }
        getConditionConfig({
            apiIdList: (state.parentNodeApiIdList || []).filter(apiId => apiId !== null && apiId !== 'message' && apiId !== 'code'),
        }).then(res => {
            const addDisabledToChildren = (items) => {
                return items.map(item => {
                    if (Reflect.has(item, 'fieldType') && item.fieldType === 'jsonArray' && Array.isArray(item.children)) {
                        // 对 children 中的每一项递归调用 addDisabledToChildren
                        item.children = addDisabledToChildren(item.children).map(child => ({
                            ...child,
                            disabled: true  // 添加 disabled 属性
                        }));
                    }
                    // 将 children 为空数组的 children 置为 null
                    item.children = item.children && item.children.length > 0 ? item.children : null;
                    return item;
                });
            };
            
            this.filedList = addDisabledToChildren(res.data);
            this.filedList = this.changeChildrenKey(this.filedList);
        }).catch(err => {
            console.log(err);
        }).finally(() => {
            this.loading = false;
        })
    },
    data() {
        return {
            filedList: [],
            loading: false,
        }
    },
    methods: {
        addCondition(index) {
            state.currentNodeInfoFront.options.conditionList.push([
                {
                    toEnName: '',
                    operate: '',
                    valueType: '',
                    value: [],
                }
            ])
        },
        deleteCondition(index) {
            if (state.currentNodeInfoFront.options.conditionList.length === 1) {
                return;
            }
            state.currentNodeInfoFront.options.conditionList.splice(index, 1)
        },
        addConditionChildren(index, indexJ) {
            state.currentNodeInfoFront.options.conditionList[index].push({
                toEnName: '',
                operate: '',
                valueType: '',
                value: [],
            })
        },
        deleteConditionChildren(index, indexJ) {
            if (state.currentNodeInfoFront.options.conditionList[index].length === 1) {
                state.currentNodeInfoFront.options.conditionList[index][0].toEnName = '';
                state.currentNodeInfoFront.options.conditionList[index][0].operate = '';
                state.currentNodeInfoFront.options.conditionList[index][0].valueType = '';
                state.currentNodeInfoFront.options.conditionList[index][0].value = [];
                return;
            }
            state.currentNodeInfoFront.options.conditionList[index].splice(indexJ, 1)
        },
        handleChange(value, i, j) {
            if (this.state.currentNodeInfoFront.options.conditionList[i][j].valueType == '3') {
                if (Reflect.has(value, 'request') && Array.isArray(value.request) && value.request.length) {
                    // 如果存在兼容性字段，则添加到兼容性列表中
                    const existingIndex = this.state._compatibilityList.findIndex(item => item.nodeUniqueId === this.state.currentNodeInfoFront.uniqueId && item.i == i && item.j == j)
                    // 如果不存在，则添加到兼容性列表中
                    if (existingIndex === -1) {
                        this.state._compatibilityList.push({
                            '_isOtherFormCondition': true,
                            'nodeUniqueId': this.state.currentNodeInfoFront.uniqueId,
                            i,
                            j
                        })
                    }
                    
                }
            }
            
            this.$set(
                this.state.currentNodeInfoFront.options.conditionList[i][j],
                'value',
                [JSON.stringify(value)]
            );
        },
        handleSelectionChange(value, i, j) {
            // 关闭下拉菜单
            this.$refs.cascaderHandle.map(item => {
                item.dropDownVisible = false;
            })
            // 重置operate,valueType,value，当有新的toEnName被选中时
            if (value) {
                // 默认选中第一项
                console.log(this.findData(this.filedList, value))
                this.$set(this.state.currentNodeInfoFront.options.conditionList[i][j], 'operate', this.findData(this.filedList, value).operateList[0]?.enName);
                this.$set(this.state.currentNodeInfoFront.options.conditionList[i][j], 'valueType', this.findData(this.filedList, value).valueTypeList[0]?.enName);
                this.$set(this.state.currentNodeInfoFront.options.conditionList[i][j], 'value', []);
            }
        },
        // 在列表中根据enName查找对应项，并返回找到的对象
        findData(list, flg) {
            for (let i of list) {
                if (i.enName === flg) {
                    return i;
                }
                if (i.children) {
                    const result = this.findData(i.children, flg);
                    if (result.enName === flg) {
                        return result;
                    }
                }
            }
            return { operateList: [], valueTypeList: [] };
        },
        changeChildrenKey(arr, parentEnName = '') {
			// 递归处理arr，将父节点的enName拼接到子节点的enName中
			if (!arr) return [];
		
			return arr.map(item => {
				// 拼接 enName
				const newItem = {
					...item,
					enName: parentEnName ? `${parentEnName}.${item.enName}` : item.enName
				};
		
				// 递归处理 children
				if (item.children) {
					newItem.children = this.changeChildrenKey(item.children, newItem.enName);
				}
		
				return newItem;
			});
		},
        // 此函数用于将已经选择的内容进行拼接用于条件卡片的展示
        changeContent() {
            // 解析 fieldType 和 value
            const parseValue = (field, j) => {
                const fieldTypeList = ['related_task', 'customer', 'product', 'linkman', 'user', 'role'];
                let value = '';
                // 如果valueType为3，则表示为来自其他表单, 需要拼接valueType为3的value
                if (j.valueType == 3) {
                    try {
                        let jsonData = JSON.parse((j?.value && Array.isArray(j?.value) && j?.value.length > 0 && j?.value[0]) || "[]");
                        value = (jsonData?.toBizTypeName || '') + '-' + (jsonData?.response?.cnName || '');
                        return value;
                    } catch (error) {
                        value = '';
                        console.error(error)
                    }
                    return value
                }
                if (field.fieldType === 'related_task') {
                    try {
                        value = JSON.parse(j?.value[0] || [])?.[0]?.taskNo || '';
                    } catch (error) {
                        value = '';
                    }
                } else if (fieldTypeList.includes(field.fieldType) || field.enName === 'tags') {
                    try {
                        value = JSON.parse(j?.value[0] || {})?.[0]?.name || '';
                    } catch (error) {
                        value = '';
                    }
                } else {
                    try {
                        const valueArr = JSON.parse(j?.value[0]);
                        if (Array.isArray(valueArr)) {
                            // 将数组中的每个元素拼接成字符串
                            value = valueArr.join(',');
                        } else {
                            value = j?.value[0] ?? '';
                        }
                    } catch (error) {
                        // 如果解析失败，则使用原始值
                        value = j?.value[0] ?? '';
                    }
                }
                return value;
            };

            // 拼接内容
            const appendContent = (field, j, value) => {
                if (field.enName === j.toEnName) {
                    const operateCnName = field.operateList.find(k => k.enName === j.operate)?.cnName || '';
                    return `${field.cnName || ''}${operateCnName}${value},`;
                }
                if (field.children) {
                    return field.children.map(child => {
                        if (child.enName === j.toEnName) {
                            const operateCnName = child.operateList.find(k => k.enName === j.operate)?.cnName || '';
                            if (j.valueType == '3') {
                                try {
                                    let jsonData = JSON.parse((j?.value && Array.isArray(j?.value) && j?.value.length > 0 && j?.value[0]) || "[]");
                                    return `${field.cnName || ''}/${child.cnName || ''}${operateCnName}${(jsonData?.toBizTypeName || '')}-${(jsonData?.response?.cnName || '')},`;
                                } catch (error) {
                                    console.error(error);
                                }
                                return ''
                            }
                            return `${field.cnName || ''}/${child.cnName || ''}${operateCnName}${j.value?.[0] ?? ''},`;
                        }
                        return '';
                    }).join('');
                }
                return '';
            };

            // 主逻辑
            let content = '';
            state.currentNodeInfoFront.options.conditionList.forEach(i => {
                i.forEach(j => {
                    this.filedList.forEach(field => {
                        if (field.enName === j.toEnName) {
                            const value = parseValue(field, j);
                            content += appendContent(field, j, value);
                        }
                        if (field.children) {
                            field.children.forEach(child => {
                                if (child.enName === j.toEnName) {
                                    const value = parseValue(child, j);
                                    content += appendContent(field, j, value);
                                }
                            });
                        }
                    });
                });
            });

            // 去掉最后一个多余的逗号
            if (content.endsWith(',')) {
                content = content.slice(0, -1);
            }

            state.currentNodeInfoFront.content = content;
        }
    }
}
</script>

<style lang="scss">
@import '@src/modules/trigger/view/setting/style/cascader.scss';
</style>

<style lang="scss" scoped>
::v-deep .el-icon-delete {
    color: #3D3D3D;
}

::v-deep .el-icon-delete:hover {
    color: red;
}

.conditional-config {
    

    &-title {
        font-size: 14px;
        margin-bottom: 16px;
    }

    .conditional-config-content {
        .conditional-config-set {
            .conditional-config-title-or {
                margin: 12px 0;
            }

            .conditional-config-set-content {
                background-color: #f9f9f9;
                border: 1px solid #E5E5E5;
                border-radius: 4px;

                &-title {
                    height: 32px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding: 8px 12px;

                    ::v-deep .el-button {
                        padding: 0;
                    }
                }

                .conditional-config-set-content-content {
                    padding: 16px 24px;

                    .conditional-config-item {
                        .conditional-config-title-and {
                            margin: 8px 0;
                        }

                        &-content {
                            &-title {
                                height: 30px;
                                display: flex;
                                align-items: center;
                                justify-content: space-between;
                                background-color: #EEEEEE;
                                border-radius: 4px;
                                padding: 4px 8px;

                                ::v-deep .el-button {
                                    padding: 0;
                                }
                            }

                            &-content {
                                display: flex;
                                flex-wrap: wrap;
                                justify-content: space-between;

                                .conditional-config-select-max {
                                    width: 100%;
                                    margin-top: 8px;
                                }

                                .conditional-config-select-small {
                                    width: calc(50% - 4px);
                                    margin-top: 8px;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>